'use strict';

const Service = require('egg').Service;
const { stateKeys } = require('../core/base_mongo_model');

const { STUDY_TIME_LINE_LIST_CATCE_KEY, STUDY_TIME_LINE_LIST_DUSTBIN_CATCE_KEY } = require('../../config/redisKey');

class StudyTimeLineService extends Service {
  async all() {
    return this.ctx.getCache(STUDY_TIME_LINE_LIST_CATCE_KEY, async () => {
      return await this.ctx.model.StudyTimeLine.find({
        $or: [
          { stateKey: stateKeys.NORMAL },
          { stateKey: { $exists: false } },
        ],
      }).sort({ date: -1 }).exec()
    })
  }

  /**
   * 创建
   */
  async create() {
    const { StudyTimeLine } = this.ctx.model;
    await this.ctx.clearCache(STUDY_TIME_LINE_LIST_CATCE_KEY)
    return await new StudyTimeLine(this.ctx.w_body()).save();
  }

  /**
   * 删除数据
   */
  async destroy() {
    const { StudyTimeLine } = this.ctx.model;
    await this.ctx.clearCache(STUDY_TIME_LINE_LIST_CATCE_KEY, STUDY_TIME_LINE_LIST_DUSTBIN_CATCE_KEY)
    return await StudyTimeLine.removeModel(this.ctx.params.id);
  }

  /**
   * 更新数据
   */
  async update() {
    const { StudyTimeLine } = this.ctx.model;
    await this.ctx.clearCache(STUDY_TIME_LINE_LIST_CATCE_KEY)
    return await StudyTimeLine.updateModel(this.ctx.params.id, this.ctx.w_body());
  }

  /**
   * 获取回收站列表
   */
  async dustbinList() {
    return this.ctx.getCache(STUDY_TIME_LINE_LIST_DUSTBIN_CATCE_KEY, async () => {
      return await this.ctx.model.StudyTimeLine.find({
        $or: [
          { stateKey: stateKeys.DUSTBIN },
        ]
      }).exec()
    })
    return data;
  }
  /**
   * 从回收站还原
   */
  async dustbinRestore() {
    const { StudyTimeLine } = this.ctx.model;
    await this.ctx.clearCache(STUDY_TIME_LINE_LIST_CATCE_KEY, STUDY_TIME_LINE_LIST_DUSTBIN_CATCE_KEY)
    const { id } = this.ctx.params;
    return await StudyTimeLine.dustbinRestore(id);
  }
  /**
   * 从回收站删除数据
   */
  async dustbinDelete() {
    const { StudyTimeLine } = this.ctx.model;
    await this.ctx.clearCache(STUDY_TIME_LINE_LIST_DUSTBIN_CATCE_KEY)
    return await StudyTimeLine.removeModel(this.ctx.params.id, true);
  }
}

module.exports = StudyTimeLineService;
